#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
修复角色挂机状态与挂机记录的数据一致性问题
"""

from database import db_manager
from datetime import datetime

def fix_idle_status_consistency():
    """
    修复角色挂机状态与挂机记录的一致性
    """
    print("=== 修复挂机状态一致性 ===")
    
    try:
        # 1. 查找所有不一致的角色
        print("\n1. 查找数据不一致的角色...")
        inconsistent_query = """
            SELECT c.id, c.name, c.is_idle, 
                   COUNT(ir.id) as active_idle_count
            FROM characters c
            LEFT JOIN idle_records ir ON c.id = ir.character_id AND ir.status = 'active'
            GROUP BY c.id, c.name, c.is_idle
            HAVING (c.is_idle = 1 AND COUNT(ir.id) != 1) 
                OR (c.is_idle = 0 AND COUNT(ir.id) != 0)
        """
        
        inconsistent_result = db_manager.execute_query(inconsistent_query)
        
        if not inconsistent_result:
            print("✅ 没有发现数据不一致的角色")
            return
        
        print(f"⚠️  发现 {len(inconsistent_result)} 个角色存在数据不一致:")
        for record in inconsistent_result:
            print(f"   角色: {record['name']} (ID: {record['id']})")
            print(f"   挂机状态: {record['is_idle']}, 活跃挂机记录: {record['active_idle_count']}")
        
        # 2. 修复策略：根据活跃挂机记录来更新角色状态
        print("\n2. 开始修复数据一致性...")
        
        for record in inconsistent_result:
            char_id = record['id']
            char_name = record['name']
            current_is_idle = record['is_idle']
            active_count = record['active_idle_count']
            
            # 根据活跃挂机记录数量决定正确的挂机状态
            correct_is_idle = 1 if active_count > 0 else 0
            
            if current_is_idle != correct_is_idle:
                print(f"\n   修复角色 {char_name}:")
                print(f"   当前挂机状态: {current_is_idle} -> 正确状态: {correct_is_idle}")
                
                # 更新角色挂机状态
                update_query = "UPDATE characters SET is_idle = %s WHERE id = %s"
                db_manager.execute_update(update_query, (correct_is_idle, char_id))
                
                print(f"   ✅ 已更新角色 {char_name} 的挂机状态")
            
            # 如果有多个活跃挂机记录，保留最新的一个
            if active_count > 1:
                print(f"\n   处理角色 {char_name} 的多个活跃挂机记录:")
                
                # 获取所有活跃记录，按开始时间排序
                active_records_query = """
                    SELECT id, start_time 
                    FROM idle_records 
                    WHERE character_id = %s AND status = 'active'
                    ORDER BY start_time DESC
                """
                active_records = db_manager.execute_query(active_records_query, (char_id,))
                
                # 保留最新的记录，其他的标记为completed
                if len(active_records) > 1:
                    latest_record_id = active_records[0]['id']
                    
                    for i, old_record in enumerate(active_records[1:], 1):
                        old_record_id = old_record['id']
                        
                        # 将旧记录标记为completed，并设置结束时间
                        complete_old_query = """
                            UPDATE idle_records 
                            SET status = 'completed', end_time = %s
                            WHERE id = %s
                        """
                        db_manager.execute_update(complete_old_query, (datetime.now(), old_record_id))
                        
                        print(f"   ✅ 已完成旧挂机记录 {old_record_id}")
                    
                    print(f"   ✅ 保留最新挂机记录 {latest_record_id}")
        
        # 3. 验证修复结果
        print("\n3. 验证修复结果...")
        verification_result = db_manager.execute_query(inconsistent_query)
        
        if not verification_result:
            print("✅ 所有数据一致性问题已修复")
        else:
            print(f"⚠️  仍有 {len(verification_result)} 个角色存在问题")
            for record in verification_result:
                print(f"   角色: {record['name']}, 挂机状态: {record['is_idle']}, 活跃记录: {record['active_idle_count']}")
        
        # 4. 显示修复后的状态
        print("\n4. 当前test用户角色状态:")
        final_status_query = """
            SELECT c.id, c.name, c.is_idle, 
                   COUNT(ir.id) as active_idle_count
            FROM characters c
            JOIN accounts a ON c.account_id = a.id
            LEFT JOIN idle_records ir ON c.id = ir.character_id AND ir.status = 'active'
            WHERE a.username = 'test'
            GROUP BY c.id, c.name, c.is_idle
        """
        
        final_result = db_manager.execute_query(final_status_query)
        
        for record in final_result:
            is_idle = record['is_idle']
            active_count = record['active_idle_count']
            status_icon = "✅" if (is_idle and active_count == 1) or (not is_idle and active_count == 0) else "⚠️"
            
            print(f"   {status_icon} 角色: {record['name']}")
            print(f"      挂机状态: {is_idle}, 活跃挂机记录: {active_count}")
        
        print("\n=== 修复完成 ===")
        
    except Exception as e:
        print(f"❌ 修复过程中发生错误: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    fix_idle_status_consistency()